import { SelectOptionData } from '@arco-design/web-vue';
import { ResultVO } from '@/api/invoice';
import { TagData } from '@arco-design/web-vue/es/input-tag/interface';
import getJSON from './requestJSON';

const getBaseUrl = async () => {
  const data: any = await getJSON('/app-config.json');
  if (data && data.VITE_API_BASE_URL) {
    return data.VITE_API_BASE_URL as string;
  }
  return import.meta.env.VITE_API_BASE_URL as string;
};
const getAuthUrl = async () => {
  const { data } = await getJSON('/app-config.json');
  if (data && data.VITE_API_AUTH_URL) {
    return data.VITE_API_AUTH_URL as string;
  }
  return import.meta.env.VITE_API_AUTH_URL as string;
};
const openwin = (url: string, width: number, height: number) => {
  const iTop = (window.screen.availHeight - 30 - height) / 2;
  const iLeft = (window.screen.availWidth - 10 - width) / 2;
  window.open(
    url,
    '',
    `height=${height}, width=${width}, top=${iTop}, left=${iLeft}`
  );
};

const getOptionFromValue = (key: string, options: SelectOptionData[]) => {
  let label = '';
  if (options) {
    options.forEach((x) => {
      if (key === x.value) {
        label = x.label as string;
      }
    });
  }
  return label;
};

/**
 * 日期有 yyyy-MM-dd HH:mm:ss 转换成 yyyy-MM-dd
 */
const dateConversion = (dateTimeStr: string): string => {
  let res = '';
  if (dateTimeStr) {
    if (dateTimeStr.indexOf(' ') !== -1) {
      // 创建一个 Date 对象
      const date = new Date(dateTimeStr);

      // 获取年、月、日
      const year = date.getFullYear();
      const month = (date.getMonth() + 1).toString().padStart(2, '0'); // 月份从 0 开始，所以要加 1
      const day = date.getDate().toString().padStart(2, '0');
      res = `${year}-${month}-${day}`;
    }
  }
  return res;
};

const changeStringToParse = (str: string) => {
  try {
    if (str && typeof str === 'string' && typeof JSON.parse(str) === 'object') {
      return JSON.parse(str);
    }
    return str;
  } catch (e) {
    // eslint-disable-next-line no-console
    console.error(e);
  }
  return str;
};
const convertTemplateToTags = (
  template: string,
  optionList: ResultVO[]
): TagData[] => {
  // 1. 使用正则表达式拆分字符串（同时捕获变量和普通文本）
  const segments = template.split(/(\$\{\w+\})/).filter(Boolean);
  const result: TagData[] = [];
  segments.forEach((segment) => {
    // 2. 检查是否为变量段（${variable}格式）
    const variableMatch = segment.match(/^\$\{(\w+)\}$/);

    if (variableMatch) {
      // 3. 处理变量段
      const variableName = variableMatch[1];
      const info = optionList.find((x) => x.id === variableName);
      result.push({
        label: info?.name, // 从映射表获取中文标签
        value: variableName, // 使用变量名作为value
        closable: true,
        type: 'select', // 标记为选择框类型
        tagProps: { color: 'red' }, // 空属性对象
      });
    } else {
      // 4. 处理普通文本段
      result.push({
        label: segment, // 直接使用文本内容
        value: segment, // value与文本相同
        closable: true,
        type: 'input', // 标记为输入框类型
      });
    }
  });
  return result;
};
const convertTemplateToStr = (
  template: string,
  optionList: ResultVO[]
): string => {
  // 1. 使用正则表达式拆分字符串（同时捕获变量和普通文本）
  const segments = template.split(/(\$\{\w+\})/).filter(Boolean);
  let result = '';
  segments.forEach((segment) => {
    // 2. 检查是否为变量段（${variable}格式）
    const variableMatch = segment.match(/^\$\{(\w+)\}$/);

    if (variableMatch) {
      // 3. 处理变量段
      const variableName = variableMatch[1];
      const info = optionList.find((x) => x.id === variableName);
      // eslint-disable-next-line no-unsafe-optional-chaining
      result += info?.name;
    } else {
      // 4. 处理普通文本段
      result += segment;
    }
  });
  return result;
};
export {
  getBaseUrl,
  getAuthUrl,
  changeStringToParse,
  openwin,
  getOptionFromValue,
  dateConversion,
  convertTemplateToTags,
  convertTemplateToStr,
};
